<template>
  <div class="registerCard">
    <el-card style="background-color: rgba(255, 255, 255, 0.9)">
      <el-form
        ref="form"
        :model="registerForm"
        label-width="80px"
        class="form-position"
      >
        <el-form-item prop="username">
          <UploadAvatar
            ref="registerAvatar"
            class="avatar-position"
            :isAdd="true"
          ></UploadAvatar>
        </el-form-item>

        <el-form-item label="用户名:" prop="username">
          <el-input
            v-model="registerForm.username"
            class="my-input"
            placeholder="请设置用户名"
            @blur="checkUserNameExist"
          ></el-input>
        </el-form-item>
        <el-form-item label="密码:" prop="password">
          <el-input
            v-model="registerForm.password"
            type="password"
            class="my-input"
            placeholder="请设置密码"
          ></el-input>
        </el-form-item>
        <el-form-item label="手机号:" prop="phonenumber">
          <el-input
            v-model="registerForm.phonenumber"
            class="my-input"
            placeholder="请输入手机号"
            @blur="checkPhoneNumberExist"
          ></el-input>
        </el-form-item>
        <el-form-item label="验证码:" prop="verificationCode">
          <el-input
            v-model="registerForm.verificationCode"
            class="code-input"
            placeholder="请输入验证码"
          ></el-input>
          <el-button
            style="margin-left: 8px; width: 120px"
            @click="sendVerificationCode"
          >
            {{ countDown > 0 ? `${countDown} 秒后重新发送` : "发送验证码" }}
          </el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="register" style="margin-left: 55px"
            >注册</el-button
          >
          <el-button type="primary" @click="toLogin" style="margin-left: 30px"
            >返回</el-button
          >
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import UploadAvatar from "../common/UploadAvatar.vue";

export default {
  created() {
    // 获取vuex中的isCountingDown和countDown
    const isCountingDown = this.$store.state.isCountingDown;
    const countDown = this.$store.state.countDown;

    // 如果正在倒计时，延续上一次的计时
    if (isCountingDown && countDown > 0) {
      this.clearTimer(); // 清除之前的定时器
      this.startCountdown(countDown);
    }
  },
  components: {
    UploadAvatar,
  },
  data() {
    return {
      registerForm: {
        username: "",
        password: "",
        phonenumber: "",
        avatar: "",
        verificationCode: "",
      },
      usernameExist: false, //用户名是否存在标识
      phonenumberExist: false, //手机号是否存在标识
      countdownTimer: null, // 新增定时器变量
      countdownSeconds: 60, //初始倒计时秒数
    };
  },
  computed: {
    isCountingDown() {
      return this.$store.state.isCountingDown;
    },
    countDown() {
      return this.$store.state.countDown;
    },
  },
  methods: {
    sendVerificationCode() {
      if (this.phonenumberExist) {
        this.$message({
          message: "发送失败，原因：该手机号已绑定另一账号",
          type: "error",
        });
        return;
      }

      // 如果正在倒计时，不执行发送验证码的逻辑
      if (this.isCountingDown) {
        return;
      }

      //验证手机号
      const regex = /^1[3456789]\d{9}$/;
      if (!regex.test(this.registerForm.phonenumber)) {
        this.$message({
          message: "手机号码不合法",
          type: "error",
        });
        return;
      }

      // 发送验证码，可以在此处调用后端接口
      console.log("发送验证码");
      this.$request.getHttp({
        url: "/sms/sendMessage",
        params: {
          number: this.registerForm.phonenumber,
        },
        success: (data) => {
          this.$message({
            message: "验证码已发送，请在1分钟内完成注册",
          });
        },
        error: (error) => {},
      });

      // 开始倒计时
      this.$store.dispatch("startCountdown");
      this.$store.dispatch("updateCountDown", this.countdownSeconds); // Set initial countdown value
      this.startCountdown(this.countdownSeconds); // 设置初始倒计时值
    },
    startCountdown(initialCount) {
      let remainingCount = initialCount;

      this.countdownTimer = setInterval(() => {
        if (remainingCount > 0) {
          remainingCount--;
          this.$store.dispatch("updateCountDown", remainingCount);
        } else {
          this.clearTimer(); // 倒计时结束后清除定时器
          this.$store.dispatch("stopCountdown"); // 倒计时结束后恢复按钮可点击状态
        }
      }, 1000);
    },
    // 清除定时器
    clearTimer() {
      clearInterval(this.countdownTimer);
    },
    register() {
      //拿到上传的图片名称
      console.log(this.$refs.registerAvatar.$data);

      //未上传头像
      if (!this.$refs.registerAvatar.$data.responseFileName) {
        this.$message({
          message: "请上传头像",
          type: "error",
        });
        return;
      }
      //表单设置头像
      this.registerForm.avatar =
        this.$refs.registerAvatar.$data.responseFileName;

      //数据合法性验证不通过
      if (!this.verifyForm()) {
        return;
      }
      // 实现注册逻辑，可以在此处调用后端接口
      this.$request.postHttp({
        url: "/user/register",
        data: this.registerForm,
        success: (data) => {
          if (data.code == 200) {
            if (data.isSaved) {
              this.$message({
                message: "注册成功！",
                type: "success",
              });
              this.$router.replace("/");
            }
          } else if (data.code == 500) {
            this.$message({
              message: data.msg,
              type: "error",
            });
          }
        },
        error: (error) => {},
      });

      // 清空表单
      // this.$refs.form.resetFields();
    },
    //验证合法性
    verifyForm() {
      const verifyUserName = /^(?![0-9]+$)[a-zA-Z0-9]{6,15}$/;
      const verifyPassWord = /^(?=.*[0-9])(?=.*[a-zA-Z])[a-zA-Z0-9]{6,15}$/;
      const verifyPhoneNumber = /^1[3456789]\d{9}$/;
      const verifyCode = /^\d{6}$/;
      //验证用户名，验证密码，验证手机号，验证码的合法性
      //验证用户名合法性
      if (!verifyUserName.test(this.registerForm.username)) {
        this.$message({
          message:
            "用户名不合法，用户名为6-15位的英文和数字组合，可以为纯英文，不能为纯数字",
          type: "error",
        });
        return false;
      }
      //用户名是否存在
      if (this.usernameExist) {
        this.$message({
          message: "用户名已经存在，请换一个试试",
          type: "error",
        });
        return false;
      }
      //验证密码合法性
      if (!verifyPassWord.test(this.registerForm.password)) {
        this.$message({
          message: "密码不合法，密码为6-15位的英文和数字组合",
          type: "error",
        });
        return false;
      }
      //验证手机号合法性
      if (!verifyPhoneNumber.test(this.registerForm.phonenumber)) {
        this.$message({
          message: "手机号不合法，请输入11位的数字的手机号",
          type: "error",
        });
        return false;
      }
      //手机号是否已经被注册
      if (this.phonenumberExist) {
        this.$message({
          message: "注册失败，该手机号已绑定另一账号",
          type: "error",
        });
        return;
      }
      //验证验证码合法性
      if (!verifyCode.test(this.registerForm.verificationCode)) {
        this.$message({
          message: "请输入6位数字的验证码",
          type: "error",
        });
        return false;
      }

      return true;
    },
    //验证用户名是否存在
    checkUserNameExist() {
      //发送请求验证是否存在该用户名
      this.$request.getHttp({
        url: "/user/isExistUserName",
        params: {
          username: this.registerForm.username,
        },
        success: (data) => {
          console.log(data);
          if (data.isExist) {
            this.$message({
              message: "用户名已经存在，换一个试试",
              type: "warning",
            });
            this.usernameExist = true;
            return;
          }
        },
        error: (error) => {},
      });
      this.usernameExist = false;
    },
    //验证手机号是否被注册了
    checkPhoneNumberExist() {
      //发送请求验证是否存在该用户名
      this.$request.getHttp({
        url: "/user/isExistPhoneNumber",
        params: {
          phonenumber: this.registerForm.phonenumber,
        },
        success: (data) => {
          console.log(data);
          if (data.isExist) {
            this.$message({
              message: "该手机号已被注册",
              type: "warning",
            });
            this.phonenumberExist = true;
            return;
          }
        },
        error: (error) => {},
      });
      this.phonenumberExist = false;
    },
    //返回
    toLogin() {
      this.$router.replace("/");
    },
  },
};
</script>

<style scoped>
.form-position {
  margin-left: 15%;
}

.avatar-position {
  padding-left: 20%;
}

.registerCard {
  width: 630px;
  height: 420px;
}

/* 可以在这里添加样式 */
.my-input {
  width: 330px;
}
.code-input {
  width: 200px;
}

.form-btn {
  display: flex;
  align-items: center;
  justify-content: space-around;
}
</style>
